package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //修改orders表（主键回显）（生成订单号，获取用户id，生成下单时间，设置冗余字段）
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);//设置点餐用户id
        orders.setOrderTime(LocalDateTime.now());//设置下单时间
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        orders.setPhone(addressBook.getPhone());//设置冗余字段电话
        orders.setAddress(addressBook.getDetail());//设置冗余字段地址
        orders.setConsignee(addressBook.getConsignee());//设置冗余字段收货人
        User user=userMapper.selectById(userId);//获取当前点餐的用户
        orders.setUserName(user.getName());//设置冗余字段用户姓名
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//使用当前时间转换为字符串作为订单号
        orderMapper.insertOne(orders);
        //修改order_detail表
        List<ShoppingCart> cartList = shoppingCartMapper.selectByUserId(userId);
        List<OrderDetail> orderDetailList=new ArrayList<>();
        for (ShoppingCart shoppingCart : cartList) {//构造准备插入的订单详情列表
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setId(null);
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //清空购物车
        shoppingCartMapper.clean(userId);
        //生成VO对象返回
        return OrderSubmitVO.builder().id(orders.getId()).orderAmount(orders.getAmount()).orderTime(orders.getOrderTime()).orderNumber(orders.getNumber()).build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        //来单通知
        Map message=new HashMap();
        message.put("type",1);
        message.put("orderId",ordersDB.getId());
        message.put("content","订单号："+outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(message));

        orderMapper.update(orders);
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        /**
         * 注意！！！
         * 在分页查询和连接查询同时使用时要小心，因为分页是对连接后的查询结果进行分页，而不是对封装后的实体类进行分页
         * 例如此处就不能使用连接查询,而要对order表进行单表查询，分页处理，然后在封装进OrderVO实体类
         */
        //对Order单表进行分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        List<Orders> ordersList=orderMapper.page(ordersPageQueryDTO);//分页前结果
        PageInfo<Orders> pageInfo=new PageInfo<>(ordersList);
        List<Orders> ordersList1 = pageInfo.getList();//分页后结果

        //将Order类装进OrderVO类中并填写orderDetailList
        List<OrderVO> orderVOList=new ArrayList<>();
        for (Orders orders : ordersList1) {
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetailMapper.selectByOrderId(orders.getId()));
            orderVOList.add(orderVO);
        }

        //封装分类结果类，返回
        return new PageResult(ordersList.size(),orderVOList);
    }

    @Override
    public OrderVO orderDetail(Long id) {
        return orderMapper.selectOrderVOById(id);
    }

    @Override
    public void cancelByUser(Long id) throws Exception {
        log.info("取消订单：{}",id);
        //查询当前订单状态
        OrderVO orderVO = orderMapper.selectOrderVOById(id);
        int status=orderVO.getStatus();
        if(status!=Orders.PENDING_PAYMENT && status!=Orders.TO_BE_CONFIRMED) { //商家接单后，退款需要电话联系商家，不能直接在系统内退款
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if(status==Orders.TO_BE_CONFIRMED) {//订单处于已支付待商家确认状态，需要进行退款
            weChatPayUtil.refund(orderVO.getNumber(),orderVO.getNumber(),orderVO.getAmount(),orderVO.getAmount());//全额退款
        }
        //将订单状态设置为已取消，并修改订单取消时间
        Orders orders=new Orders();
        orders.setId(id);
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    @Override
    public void refundSuccess(String outRefundNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outRefundNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .payStatus(Orders.REFUND)
                .build();

        orderMapper.update(orders);
    }

    @Override
    public void repetition(Long id) {
        //查找id对应的订单
        OrderVO orderVO = orderMapper.selectOrderVOById(id);
        //将订单详情加入购物车表中
        List<OrderDetail> orderDetailList = orderVO.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart=new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setUserId(orderVO.getUserId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            if(shoppingCartMapper.insertOne(shoppingCart)==0) { //新增购物车失败
                throw new ShoppingCartBusinessException(MessageConstant.UNKNOWN_ERROR);
            }
        }
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        log.info("分页搜索：{}",ordersPageQueryDTO);
        //对Order单表进行分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        List<Orders> ordersList=orderMapper.page(ordersPageQueryDTO);//分页前结果
        PageInfo<Orders> pageInfo=new PageInfo<>(ordersList);
        List<Orders> ordersList1 = pageInfo.getList();//分页后结果

        //将Order类装进OrderVO类中并填写orderDetailList
        List<OrderVO> orderVOList=new ArrayList<>();
        for (Orders orders : ordersList1) {
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetailMapper.selectByOrderId(orders.getId()));
            orderVOList.add(orderVO);
        }

        for (OrderVO orderVO : orderVOList) { //生成包含菜品的字符串
            orderVO.setOrderDishes(generateDishStr(orderVO.getOrderDetailList()));
        }
        return new PageResult(ordersList.size(),orderVOList);
    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(orderMapper.getCountByStatus(Orders.CONFIRMED));//统计待派送
        orderStatisticsVO.setToBeConfirmed(orderMapper.getCountByStatus(Orders.TO_BE_CONFIRMED));//统计待接单
        orderStatisticsVO.setDeliveryInProgress(orderMapper.getCountByStatus(Orders.DELIVERY_IN_PROGRESS));//统计派送中
        return orderStatisticsVO;
    }

    @Override
    public OrderVO details(Long id) {
        return orderMapper.selectOrderVOById(id);
    }

    @Override
    public void confirm(Orders orders) {
        orders.setStatus(Orders.CONFIRMED);//将对应订单的状态修改为已接单即可
        orderMapper.update(orders);
    }

    @Override
    public void rejection(Orders orders) throws Exception {
        OrderVO orderVO = orderMapper.selectOrderVOById(orders.getId());
        if(orderVO.getStatus().equals(Orders.TO_BE_CONFIRMED)) { //只有处于待接单状态的订单可以拒单
            if(orderVO.getPayStatus().equals(Orders.PAID)) { //订单已支付，需要进行退款
                weChatPayUtil.refund(orderVO.getNumber(),orderVO.getNumber(),orderVO.getAmount(),orderVO.getAmount());//全额退款
            }
            //设置状态和拒单原因和取消时间
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException("只有处于待接单状态的订单可以拒单");
        }
    }

    @Override
    public void cancelByAdmin(Orders orders) throws Exception {
        OrderVO orderVO = orderMapper.selectOrderVOById(orders.getId());
        if(orderVO.getPayStatus().equals(Orders.PAID)) { //已支付，进行退款
            weChatPayUtil.refund(orderVO.getNumber(),orderVO.getNumber(),orderVO.getAmount(),orderVO.getAmount());//全额退款
        }
        //修改状态
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        OrderVO orderVO = orderMapper.selectOrderVOById(id);
        Orders orders=new Orders();
        if(orderVO.getStatus().equals(Orders.CONFIRMED)) { //只有已接单（待派送）的单子才可以进行派送
            orders.setId(id);
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        } else {
            throw new OrderBusinessException("只有处于已接单状态的单子才可以进行派送");
        }
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        OrderVO orderVO = orderMapper.selectOrderVOById(id);
        Orders orders=new Orders();
        if(orderVO.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) { //只有派送中的单子才可以完成
            orders.setId(id);
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
        } else {
            throw new OrderBusinessException("只有处于派送中状态的单子才可以完成");
        }
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Map message=new HashMap();
        OrderVO orderVO = orderMapper.selectOrderVOById(id);
        if(orderVO==null||orderVO.getStatus()!=Orders.TO_BE_CONFIRMED) {//没找到订单或订单的状态不为待接单
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        message.put("type",2);
        message.put("orderId",id);
        message.put("content","订单号:"+orderVO.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(message));
    }

    /**
     * 根据OrderDetail数组生成包含菜品的字符串
     * @param orderDetailList
     * @return
     */
    private String generateDishStr(List<OrderDetail> orderDetailList) {
        StringBuilder sb=new StringBuilder();
        for (OrderDetail orderDetail : orderDetailList) {
            sb.append(orderDetail.getName()+"*"+orderDetail.getNumber()+";");
        }
        return sb.toString();
    }

}
